package xc;

public class demo4 {
    // 将 desk 类改为静态内部类
    public static class desk {
        public static int foodflag = 0;
        public static int count = 10;
        public static final Object obj = new Object();
    }

    public static class cook extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (desk.obj) {
                    if (desk.count == 0) {
                        //System.out.println("厨师：食物已售罄，下班啦！");
                        break;
                    }
                    if (desk.foodflag == 1) {
                        try {
                            //System.out.println("厨师：已有食物，等待食客吃完...");
                            desk.obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        System.out.println("厨师：做了 1 个食物");
                        desk.foodflag = 1;
                        desk.obj.notifyAll();
                    }
                }
            }
        }
    }

    public static class eat extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (desk.obj) {
                    if (desk.count == 0) {
                        //System.out.println("食客：没有食物了，离开啦！");
                        break;
                    }
                    if (desk.foodflag == 0) {
                        try {
                            //System.out.println("食客：没有食物，等待厨师做饭...");
                            desk.obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        desk.count--;
                        System.out.println("食客：吃了 1 个食物，还有 " + desk.count + " 个可以吃。");
                        desk.foodflag = 0;
                        desk.obj.notifyAll();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        cook c = new cook();
        eat e = new eat();
        c.setName("cook");
        e.setName("eater");
        c.start();
        e.start();
    }
}